package haoji_juc;

import org.omg.CORBA.INTERNAL;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @program: Dome
 * @description:
 * @className: DomeReadWriteLock
 * @author: rjt99999
 * @version: 1.0.0
 * @create: 2020-08-04 20:54
 **/
public class DomeReadWriteLock {

    /*
     * 1. ReadWriteLock : 读写锁
     *
     * 写写/读写 需要“互斥”
     * 读读 不需要互斥
     *
     *
     * 提高效率*
     *
     */
    public static void main(String[] args) {
        readWrite readWrite = new readWrite();

        //读操作
        for (int i = 0; i < 20; i++) {

            new Thread(() -> readWrite.get(), "读").start();
        }

        //写操作
        new Thread(() -> {


            for (int i = 0; i < 10; i++) {

                readWrite.weite((int) (Math.random() * 100));

            }
        }, "写").start();


    }


}

class readWrite {


    int a = 1;

    //Lock lock = new ReentrantLock();
    //接口     juc lock 包下
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();//实现类

    public void get() {

        readWriteLock.readLock().lock();//读锁


        try {
            System.out.println(Thread.currentThread().getName() + ": " + a);
        } finally {
            readWriteLock.readLock().unlock();
        }


    }

    public void weite(int a) {

        readWriteLock.writeLock().lock(); //写锁


        try {
            System.out.println(Thread.currentThread().getName() + ": " + a);

            this.a = a;
        } finally {

            readWriteLock.writeLock().unlock();
        }


    }


}


